<template>
  <d2-container>
    <el-row :gutter="20">
      <!--<el-col :span="5">-->
        <!--<el-scrollbar class="w-full h-full">-->
          <!--<area-tree @nodeChange="treeNodeChange"></area-tree>-->
        <!--</el-scrollbar>-->
      <!--</el-col>-->
      <el-col :span="24">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="区域：">
              <el-input placeholder="请选择区域"
                        class="filter-item"
                        style="width:180px;"
                        size="small"
                        @click.native="visible = true"
                        v-model="dataForm.areaName">
              </el-input>
            </el-form-item>
            <el-form-item class="el-form-item--mini">
              <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:16px;" @click="getList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="grid grid-cols-3 gap-4" v-loading="loading">
          <div v-for="(i, index) in list" :key="index" style="background-color:rgba(0,0,0,.1);" class="theme-front-color">
            <div class="p-3 flex items-center pb-0">
              <span class="flex-1">{{ i.meter_name }}</span>
              <span class="text-sm">{{ i.meter_code }}</span>
            </div>
            <div class="p-3 flex items-center pb-0">
              <span class="flex-1">采集时间</span>
              <span class="text-sm">{{ i.ctime }}</span>
            </div>
            <div class="p-3">
              <div v-for="(j, inx) in i.collects" :key="inx" class="flex items-center">
                <img :src="j.collect_pic" class="w-8 h-8 object-contain" />
                <span class="flex-1 ml-2">{{ j.collect_name }}</span>
                <span>{{ j.collect_value }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      title="选择地域"
      :close-on-click-modal="false" width="800px" custom-class="custom-height-dialog"
      :visible.sync="visible">
      <area-tree @nodeChange="treeNodeChange"></area-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">确 定</el-button>
      </div>
    </el-dialog>

  </d2-container>
</template>

<script>
  import d2HeaderFullscreen from '../../layout/header-aside/components/header-fullscreen'
  import { mapGetters } from 'vuex'
  import areaTree from '../energyAnalysis/compont/area_tree_onceclick'
  export default {
    name: 'energyUse',
    data() {
      return {
        building:'',
        visible:false,
        socket: null,
        buildList:[],
        dataForm:{
          energyType: '',
          date:new Date(),
          dateType: 'date',
          areaName:''
        },
        meterTypeList:[],
        loading: false,
        list: [],
      }
    },
    computed: {
      ...mapGetters('d2admin/theme', ['activeSetting'])
    },
    components: {
      areaTree,
      d2HeaderFullscreen
    },
    created() {
      this.connect();
      this.getBuildDeviceList()
    },
    beforeDestroy() {
      if (this.socket) {
        console.log("beforeDestroy webSocketServer close");
        this.socket.close(); // 关闭连接
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.socket) {
        console.log("webSocketServer close");
        this.socket.close()
        next()
      }
    },
    methods: {
      getBuildDeviceList(){
        this.$api.okhttp({
          url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
          method: "get",
          params: this.$http.adornParams({
            customerId: this.$util.cookies.get("customer_id"),
            projectid:this.$util.cookies.get("cuuren_projectId")
          })
        }).then((data) => {
          if (data && data.code === 0) {
            if(data.menuList.length>0){
              let currentbuildInfo = data.menuList[0];
              this.building = currentbuildInfo.buildingId
              this.dataForm.areaName = currentbuildInfo.buildingName
              this.getList()
            }
          } else {
          }
        });
      },
      connect() {
        let baseUrl = process.env.VUE_APP_API
        if(baseUrl.indexOf("http")!= -1) {
          console.log(11111111, baseUrl.replace('http', 'ws') + 'webSocketServer')
          this.socket = new WebSocket(baseUrl.replace('http', 'ws') + 'webSocketServer');
        }else{
          baseUrl = "ws://"+window.location.hostname+":8012/webSocketServer";
          console.log(22222, baseUrl)
          this.socket = new WebSocket(baseUrl);
        }

        this.socket.onopen = () => {
          console.log('WebSocket connection established');
        };

        this.socket.onmessage = (event) => {
        //  console.log('WebSocket onmessage',event);
          const message = JSON.parse(event.data);
          this.list = message.data && message.data.devices || []
        };

        this.socket.onerror = (error) => {
          console.error('WebSocket error:', error);
        };

        this.socket.onclose = () => {
          console.log('WebSocket connection closed');
        };
      },
      sendMessage(param) {
          //实时监测
          this.socket.send(JSON.stringify({ messType:"realtime",messContent: param }));
      },
      treeNodeChange(data,buildingName){
        console.log(data,buildingName)
        this.building = data
        this.dataForm.areaName = buildingName
        this.getList()
      },
      getList() {
        this.loading = true
        let param = {
          buildingId: this.building,
          meterType: '0A0000',
          meterCode: '',
          hostname: window.location.hostname
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/services/device'),
          method: 'get',
          params: this.$http.adornParams(param)
        }).then(res => {
          this.sendMessage(param)
          if (res.code === 0) {
            this.list = res.data && res.data.devices || []
          } else {
            this.$message.error(res.msg)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{paramValue,paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
    },
  }
</script>

<style>
  /*.custom-height-dialog .el-dialog__wrapper .el-dialog {*/
    /*height: 20vh; !* 使用视窗单位 vh 来设定高度 *!*/
  /*}*/

  .custom-height-dialog .el-dialog__body {
    /* 如果需要对 body 部分单独设置高度 */
    height: calc(60vh); /* 减去头部和底部的距离，根据实际情况调整 */
    overflow-y: auto;
  }
</style>
